var express = require('express');
var router = express.Router();
var Admin = require('../db/admin.js');
var User = require('../db/user.js');
var article = require('../db/article.js');
var dynamic = require('../db/dynamic.js');
var Notice = require('../db/notice.js');


//删除公告
router.post("/deleteNotice", function (req, res, next) {
    Notice.deleteOne({ time: req.body.time }, function (err) {
        if (err) { console.log(err);; return; }
        res.send("删除成功");
    })
});

//获取历史公告
router.post("/getNotices", function (req, res, next) {
    Notice.find({}, function (err, data) {
        if (err) { console.log(err);; return; }
        let list = [];
        for (let i = 0; i < data.length; i++) {
            list.push({
                time: data[i].time,
                content: data[i].content,
            })
        }
        res.send(list);
    })
});

//发布公告
router.post("/doNotice", function (req, res, next) {
    let notice = Notice({
        aid: req.cookies.adminID,
        time: req.body.time,
        content: req.body.content,
    });
    notice.save(function (err, data) {
        if (err) { res.send("发布失败，请重试！"); return; }
        res.send("发布成功");
    });
});

//删除文章
router.post("/deleleArticle", function (req, res, next) {
    article.deleteOne({ a_id: req.body.aid }, function (err) {
        if (err) { console.log(err); return; }
        res.send("删除成功！")
    });
});

//删除用户
router.post("/deleteUser", function (req, res, next) {
    User.deleteOne({ uid: req.body.uid }, function (err) {
        if (err) { console.log(err); return; }
        res.send("删除成功！")
    });
});

//查询文章
router.post("/findArticle", function (req, res, next) {
    if (req.body.username == "" && req.body.articletitle == "") {
        article.find({}, function (err, data) {
            if (err) { console.log(err); return; }
            let articleList = [];
            for (let i = 0; i < data.length; i++) {
                articleList.push({
                    key: data[i].a_id,
                    title: data[i].title,
                    author: data[i].uname,
                    type: data[i].a_type,
                    viewNum: data[i].viewCount,
                    collectionNum: data[i].collectionCount.length,
                    commentNum: data[i].comment.length,
                })
            }
            res.send(articleList);
        });
    } else if (req.body.username != "" && req.body.articletitle == "") {
        article.find({ uname: req.body.username }, function (err, data) {
            if (err) { console.log(err); return; }
            let articleList = [];
            for (let i = 0; i < data.length; i++) {
                articleList.push({
                    key: data[i].a_id,
                    title: data[i].title,
                    author: data[i].uname,
                    type: data[i].a_type,
                    viewNum: data[i].viewCount,
                    collectionNum: data[i].collectionCount.length,
                    commentNum: data[i].comment.length,
                })
            }
            res.send(articleList);
        })
    } else if (req.body.username == "" && req.body.articletitle != "") {
        article.find({ title: req.body.articletitle }, function (err, data) {
            if (err) { console.log(err); return; }
            let articleList = [];
            for (let i = 0; i < data.length; i++) {
                articleList.push({
                    key: data[i].a_id,
                    title: data[i].title,
                    author: data[i].uname,
                    type: data[i].a_type,
                    viewNum: data[i].viewCount,
                    collectionNum: data[i].collectionCount.length,
                    commentNum: data[i].comment.length,
                })
            }
            res.send(articleList);
        });
    } else {
        article.find({ uname: req.body.username, title: req.body.articletitle }, function (err, data) {
            if (err) { console.log(err); return; }
            let articleList = [];
            for (let i = 0; i < data.length; i++) {
                articleList.push({
                    key: data[i].a_id,
                    title: data[i].title,
                    author: data[i].uname,
                    type: data[i].a_type,
                    viewNum: data[i].viewCount,
                    collectionNum: data[i].collectionCount.length,
                    commentNum: data[i].comment.length,
                })
            }
            res.send(articleList);
        });
    }
});

//查询用户
router.post("/findUser", function (req, res, next) {
    // console.log(req.cookies.adminID);
    if (req.body.name == "") {
        User.find({}, function (err, data) {
            if (err) { console.log(err); return; }
            async function doFindUsers() {
                let UserList = [];
                // console.log(data.length);
                for (let i = 0; i < data.length; i++) {
                    await article.find({ uid: data[i].uid }, function (err, art) {
                        if (err) { console.log(err); return; }
                        UserList.push({
                            key: data[i].uid,
                            imgHead: data[i].img_head != null ? "http://localhost:3000/" + data[i].img_head : "",
                            name: data[i].uname,
                            sex: data[i].sex == 1 ? "男" : "女",
                            age: "18岁",
                            follows: data[i].follows.length,
                            fans: data[i].fans.length,
                            articlesNum: art.length,
                        })
                    });
                    await dynamic.find({ uid: data[i].uid }, function (err, dyn) {
                        if (err) { console.log(err); return; }
                        if (!data[i].dynamicsNum) {
                            UserList[i]["dynamicsNum"] = dyn.length;
                        }
                    })

                }
                return UserList;
            }
            doFindUsers().then(result => {
                // console.log(result.length);
                res.send(result)
            });
        });
    } else {
        User.find({ uname: req.body.name }, function (err, data) {
            if (err) { console.log(err); return; }
            // console.log(data);
            async function doFindUsers() {
                let UserList = [];
                for (let i = 0; i < data.length; i++) {
                    await article.find({ uid: data[i].uid }, function (err, art) {
                        if (err) { console.log(err); return; }
                        UserList.push({
                            key: data[i].uid,
                            imgHead: "http://localhost:3000/" + data[i].img_head,
                            name: data[i].uname,
                            sex: data[i].sex == 1 ? "男" : "女",
                            age: "18岁",
                            follows: data[i].follows.length,
                            fans: data[i].fans.length,
                            articlesNum: art.length,
                        })
                    });
                    await dynamic.find({ uid: data[i].uid }, function (err, dyn) {
                        if (err) { console.log(err); return; }
                        if (!data[i].dynamicsNum) {
                            UserList[i]["dynamicsNum"] = dyn.length;
                        }
                    })

                }
                return UserList;
            }
            doFindUsers().then(result => {
                // console.log(result);
                res.send(result)
            });
        });
    }
});

//退出登录
router.post("/dologout", function (req, res, next) {
    res.json({
        data: "已登出",
        aid: req.cookies.adminID,
    });
});

//登录
router.post("/dologin", function (req, res, next) {
    Admin.findOne({ account: req.body.username, pwd: req.body.password }, function (err, data) {
        if (err) { console.log(err); return; }
        if (data == null) {
            res.json({ data: "账户或密码错误" });
        } else {
            res.cookie("adminID", data.aid, { httpOnly: true });
            res.json({
                data: "登录成功",
                aid: data.aid,
                name: data.name,
            });
        }
    });
});

module.exports = router;